package com.gnrsoft.springboot_test.commons.http;

import javax.annotation.Resource;

import org.apache.http.conn.HttpClientConnectionManager;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class IdleConnectionEvictor extends Thread {

	@Resource
	private HttpClientConnectionManager connectionManager;

	private volatile boolean shutdown;

	public IdleConnectionEvictor() {
		super();
		super.start();
	}

	@Override
	public synchronized void start() {
		try {

			while (!shutdown) {
				synchronized (this) {
					wait(5000);
					// 关闭失效的连接
					connectionManager.closeExpiredConnections();
				}
			}

		} catch (Exception e) {
			log.error("IdleConnectionEvictor closeExpiredConnections error ", e);
		}
	}

	/**
	 * 关闭清理无效的连接
	 */
	public void shutdown() {
		shutdown = true;
		synchronized (this) {
			notifyAll();
		}
	}
}
